<template>
  <div id="contentBox">
    <div style="text-align:center">
      <el-input v-model="form.questionnaireName" placeholder="请填写问卷名字" />
    </div>
    <div style="text-align:center">
      <el-button type="primary" @click="handleAddQuestions">添加问题</el-button>
    </div>
    <div
      v-for="(item,index) in questionList"
      :key="index"
      class="quslist"
      style="border-bottom:1px solid #666666;padding-bottom:15px;width"
    >
      <div class="everyQus">
        <h3>{{ item.topicName }}</h3>
        <div>
          <i class="el-icon-edit-outline" @click="handleEditQues(item)" />
          <i class="el-icon-delete" @click="handleDelQues(item,index)" />
        </div>
      </div>
      <div
        style="width: 60%;margin: 0px auto;display: flex;flex-direction: column;justify-content: space-between;"
      >
        <el-radio
          v-for="(item1,index1) in item.answers"
          :key="index1"
          :label="item1.answerName"
        >{{ item1.answerName }}</el-radio>
      </div>
    </div>
    <div style="width:60%;margin:0 auto;text-align:center;margin-top:15px">
      <el-button type="primary" @click="createQuestions">{{ isCreate }}</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="questionsDialogVisible"
      width="650px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :rules="formRules" :model="form" label-width="80px">
        <el-form-item label="问题题目" prop="topicName">
          <el-input v-model="form.topicName" type="textarea" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="问题类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="问题选项">
          <div v-for="(item,index) in answers" :key="index" class="addQusOptions">
            <el-input v-model="item.answerName" maxlength="50" show-word-limit />
            <el-button type="success" size="mini" icon="el-icon-plus" circle @click="addQusOptins" />
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-minus"
              circle
              @click="removeQusOptions(index)"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">添加</el-button>
        <el-button @click="questionsDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as Question from '@/api/questions'
export default {
  name: 'QuestionsAdd',
  data() {
    return {
      formRules: {
        type: [
          { required: true, message: '请选择问题类型', trigger: 'change' }
        ],
        questionnaireName: [
          { required: true, message: '请输入题目', trigger: 'blur' }
        ]
      },
      sortNum: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
      questionsDialogVisible: false, // 添加问卷模态框
      title: '添加问题',
      isCreate: '创建',
      orgId: 0,
      id: '', // 题目id
      questId: '', // 问卷id
      form: {
        questionnaireName: '', // 问卷名称
        code: '', // 表示用于模块
        topicName: '', // 题目名称
        topicNumber: '', // 题目序号
        type: '1' // 题目类型（1.单选、2.多选、3.简单题）
      },
      answers: [], // 答案列表
      deepCopyAnswers: [], // 拷贝答案列表
      questionList: [] // 问题+答案列表
    }
  },
  watch: {
    'form.type': {
      handler: function() {
        if (this.form.type === '1') {
          this.answers = [
            { answerNumber: '', answerName: '' },
            { answerNumber: '', answerName: '' }
          ]
        } else if (this.form.type === '2') {
          this.answers.push({ answerNumber: '', answerName: '' })
        }
      }
    }
  },
  mounted() {},
  methods: {
    getQuestionsList() {
      Question.questionsDetail({ id: this.$route.query.id }).then((res) => {
        this.form.questionnaireName = res.data.questionnaireName
        this.questionList = res.data.topics
      })
    },
    // 添加问题
    handleAddQuestions() {
      this.title = '添加问题'
      this.questionsDialogVisible = true
      this.form.type = '1'
      this.form.topicName = ''
      // this.form.topicNumber = "";
      this.answers = [
        { answerNumber: '', answerName: '' },
        { answerNumber: '', answerName: '' }
      ]
    },
    // 编辑问题
    handleEditQues(item) {
      console.log(item)
      this.title = '编辑问题'
      this.questionsDialogVisible = true
      this.form.topicName = item.topicName
      this.form.type = item.type + ''
    },
    // 添加问题选项
    addQusOptins() {
      this.answers.push({ answerNumber: '', answerName: '' })
    },
    // 删除问题选项
    removeQusOptions(index) {
      console.log(this.answers.length)
      if (this.answers.length >= 3 && this.form.type === 1) {
        this.answers.splice(index, 1)
        return
      } else if (this.answers.length >= 4 && this.form.type === 2) {
        this.answers.splice(index, 1)
        return
      }
    },
    // 删除问题
    handleDelQues(item, index) {
      if (this.$route.meta.title === '新建问卷') {
        this.$confirm('确定删除此问题？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.questionList.splice(index, 1)
          this.$message.success('删除成功!')
        })
      }
    },
    // 提交问卷
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.answers.forEach((item, index) => {
            item['answerNumber'] = this.sortNum[index]
          })
          console.log('问题选项', this.answers)
          this.deepCopyAnswers = JSON.parse(JSON.stringify(this.answers))
          this.questionList.push({
            topicName: this.form.topicName,
            type: +this.form.type,
            answers: this.deepCopyAnswers
          })
          this.questionList.forEach((item, index) => {
            item.topicNumber = `${index + 1}`
          })
          console.log('每个题目的题目和选项', this.questionList)
          this.questionsDialogVisible = false
          this.$refs[formName].clearValidate()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 保存问卷
    createQuestions() {
      if (this.form.questionnaireName.trim() === '') {
        this.$message.error('请填写问卷名字!')
        return
      }
      if (this.questionList.length <= 0) {
        this.$message.error('请创建问卷题目!')
        return
      }
      const dataObj = {
        questionnaireName: this.form.questionnaireName,
        orgId: this.orgId,
        code: '1',
        topics: [...this.questionList]
      }
      Question.addQuestionsList(dataObj).then((res) => {
        if (res.code === '200') {
          this.$message.success('添加问卷成功!')
          this.form.questionnaireName = ''
          this.questionList.length = 0
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ name: 'QuestionsList' })
        }
      })
    },
    handleBack() {
      this.$confirm('此操作将不会保存问卷？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(-1)
      })
    }
  }
}
</script>

<style lang='scss' scoped>
#contentBox {
  padding: 10px 20px;
}
.el-input {
  width: 400px;
  margin-bottom: 15px;
}
.el-radio {
  margin-bottom: 10px;
}
.addQusOptions .el-button {
  margin-left: 10px;
}
/deep/ .el-dialog__footer {
  text-align: left;
}
/deep/ .el-dialog__footer {
  padding: 0 30px 30px 30px;
}
.el-form-item__content > .el-input {
  margin-bottom: 0;
}
.quslist {
  width: 100%;
  .everyQus {
    margin: 0 auto;
    width: 60%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    i {
      font-size: 20px;
      margin: 0 5px;
      cursor: pointer;
    }
  }
}
</style>
